<template>
  <div class="field-id-fix-test">
    <el-card>
      <template #header>
        <h3>字段ID修复测试</h3>
      </template>
      
      <el-alert
        title="修复说明"
        type="success"
        description="修复了字段ID类型错误的问题：新字段和默认字段不再使用包含小数的字符串ID，避免后端Long类型转换错误"
        show-icon
        :closable="false"
      />
      
      <el-divider />
      
      <el-row :gutter="24">
        <!-- 测试区块选择 -->
        <el-col :span="8">
          <h4>选择测试区块</h4>
          <el-select v-model="selectedBlockId" placeholder="请选择区块" @change="loadBlockInfo">
            <el-option
              v-for="block in blocks"
              :key="block.id"
              :label="`${block.name} (${block.type})`"
              :value="block.id"
            />
          </el-select>
          
          <div v-if="selectedBlock" style="margin-top: 16px;">
            <el-descriptions border :column="1" size="small">
              <el-descriptions-item label="区块名称">{{ selectedBlock.name }}</el-descriptions-item>
              <el-descriptions-item label="区块类型">{{ selectedBlock.type }}</el-descriptions-item>
              <el-descriptions-item label="区块ID">{{ selectedBlock.id }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-col>
        
        <!-- 字段操作测试 -->
        <el-col :span="16">
          <h4>字段操作测试</h4>
          <el-space wrap style="margin-bottom: 16px;">
            <el-button @click="testAddField" :disabled="!selectedBlockId">
              测试添加字段
            </el-button>
            <el-button @click="testInitDefaultFields" :disabled="!selectedBlockId">
              测试初始化默认字段
            </el-button>
            <el-button @click="testSaveFields" :disabled="!selectedBlockId" :loading="saving">
              测试保存字段
            </el-button>
            <el-button @click="loadCurrentFields" :disabled="!selectedBlockId" :loading="loading">
              重新加载字段
            </el-button>
          </el-space>
          
          <!-- 当前字段列表 -->
          <div v-loading="loading">
            <h5>当前字段列表 ({{ testFields.length }}个)</h5>
            <el-table :data="testFields" border size="small" style="margin-bottom: 16px;">
              <el-table-column label="ID" width="200">
                <template #default="{ row }">
                  <el-tag v-if="row.id" :type="typeof row.id === 'number' ? 'success' : 'warning'">
                    {{ row.id }} ({{ typeof row.id }})
                  </el-tag>
                  <el-tag v-else-if="row._tempId" type="info">
                    {{ row._tempId }} (临时)
                  </el-tag>
                  <el-tag v-else type="danger">无ID</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="字段名" width="120" />
              <el-table-column prop="label" label="标签" width="120" />
              <el-table-column prop="type" label="类型" width="100" />
              <el-table-column label="操作" width="100">
                <template #default="{ row, $index }">
                  <el-button size="small" type="danger" @click="removeTestField($index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
      
      <el-divider />
      
      <!-- 测试结果 -->
      <h4>测试结果</h4>
      <div class="test-results">
        <div v-for="(result, index) in testResults" :key="index" class="test-result">
          <el-alert
            :title="result.title"
            :type="result.type"
            :description="result.description"
            show-icon
            :closable="false"
          />
        </div>
      </div>
      
      <el-divider />
      
      <!-- 修复前后对比 -->
      <h4>修复前后对比</h4>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <h5 style="color: #f56c6c;">修复前（错误）</h5>
            </template>
            <el-code language="javascript" style="font-size: 12px;">
{
  "id": "default_1753514651235_0.21134547975606055",  // ❌ 字符串包含小数
  "name": "title",
  "label": "标题",
  "type": "text"
}
            </el-code>
            <p style="color: #f56c6c; margin-top: 8px;">
              ❌ 后端无法将包含小数的字符串转换为Long类型
            </p>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <h5 style="color: #67c23a;">修复后（正确）</h5>
            </template>
            <el-code language="javascript" style="font-size: 12px;">
{
  // 新字段：不设置ID，让后端自动生成
  "name": "title",
  "label": "标题", 
  "type": "text"
}

// 或者已有字段：
{
  "id": 1234567890,  // ✅ 数字类型ID
  "name": "title",
  "label": "标题",
  "type": "text"
}
            </el-code>
            <p style="color: #67c23a; margin-top: 8px;">
              ✅ 后端可以正确处理数字ID或自动生成新ID
            </p>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { blockApi } from '@/api/block'

// 响应式数据
const selectedBlockId = ref<number | null>(null)
const blocks = ref<any[]>([])
const testFields = ref<any[]>([])
const loading = ref(false)
const saving = ref(false)
const testResults = ref<any[]>([])

// 计算属性
const selectedBlock = computed(() => {
  return blocks.value.find(block => block.id === selectedBlockId.value)
})

// 方法
const addTestResult = (title: string, type: 'success' | 'warning' | 'error' | 'info', description: string) => {
  testResults.value.unshift({
    title,
    type,
    description,
    time: new Date().toLocaleTimeString()
  })
  
  // 只保留最近8条结果
  if (testResults.value.length > 8) {
    testResults.value = testResults.value.slice(0, 8)
  }
}

const loadBlocks = async () => {
  try {
    const response = await blockApi.getList({ current: 1, size: 100 })
    if (response.code === 0) {
      blocks.value = response.data?.records || response.data?.list || []
      addTestResult('加载区块列表', 'success', `成功加载${blocks.value.length}个区块`)
    }
  } catch (error) {
    addTestResult('加载区块列表', 'error', '加载失败')
  }
}

const loadBlockInfo = () => {
  if (selectedBlockId.value) {
    loadCurrentFields()
  }
}

const loadCurrentFields = async () => {
  if (!selectedBlockId.value) return
  
  loading.value = true
  try {
    const response = await blockApi.getFields(selectedBlockId.value)
    if (response.code === 0) {
      testFields.value = response.data || []
      addTestResult('加载字段', 'success', `成功加载${testFields.value.length}个字段`)
    } else {
      addTestResult('加载字段', 'warning', response.msg || '加载失败')
    }
  } catch (error) {
    addTestResult('加载字段', 'error', '加载失败')
  } finally {
    loading.value = false
  }
}

const testAddField = () => {
  const newField = {
    _tempId: `temp_${Date.now()}`, // 临时ID，保存时会被删除
    name: `test_field_${testFields.value.length + 1}`,
    label: `测试字段${testFields.value.length + 1}`,
    type: 'text',
    description: '这是一个测试字段',
    required: false,
    orderNum: testFields.value.length + 1,
    status: 1
  }
  
  testFields.value.push(newField)
  addTestResult('添加字段', 'info', `添加了测试字段：${newField.label}`)
}

const testInitDefaultFields = async () => {
  if (!selectedBlock.value) return
  
  try {
    const response = await blockApi.getDefaultFields(selectedBlock.value.type)
    if (response.code === 0 && response.data && response.data.length > 0) {
      // 模拟初始化默认字段（不设置ID）
      const defaultFields = response.data.map((field: any) => ({
        ...field,
        _tempId: `default_temp_${Date.now()}_${Math.random()}`, // 临时ID
        options: field.options ? JSON.parse(field.options) : []
      }))
      
      testFields.value = [...testFields.value, ...defaultFields]
      addTestResult('初始化默认字段', 'success', `添加了${defaultFields.length}个默认字段`)
    } else {
      addTestResult('初始化默认字段', 'warning', '该类型暂无默认字段模板')
    }
  } catch (error) {
    addTestResult('初始化默认字段', 'error', '获取默认字段失败')
  }
}

const testSaveFields = async () => {
  if (!selectedBlockId.value) return
  
  saving.value = true
  try {
    // 模拟保存前的数据处理
    const fieldsData = testFields.value.map(field => {
      const fieldData: any = {
        ...field,
        options: field.options && field.options.length > 0 ? JSON.stringify(field.options) : null
      }
      
      // 删除临时ID
      if (fieldData._tempId) {
        delete fieldData._tempId
      }
      
      // 如果ID是字符串格式（临时ID），则删除ID让后端自动生成
      if (typeof fieldData.id === 'string' && (
        fieldData.id.startsWith('new_') || 
        fieldData.id.startsWith('default_') ||
        fieldData.id.includes('.')
      )) {
        delete fieldData.id
      }
      
      return fieldData
    })
    
    console.log('准备保存的字段数据:', fieldsData)
    
    const response = await blockApi.saveFields(selectedBlockId.value, fieldsData)
    if (response.code === 0) {
      addTestResult('保存字段', 'success', `成功保存${fieldsData.length}个字段`)
      await loadCurrentFields() // 重新加载以获取后端生成的ID
    } else {
      addTestResult('保存字段', 'error', response.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存字段失败:', error)
    addTestResult('保存字段', 'error', '保存失败: ' + (error.message || '未知错误'))
  } finally {
    saving.value = false
  }
}

const removeTestField = (index: number) => {
  const field = testFields.value[index]
  testFields.value.splice(index, 1)
  addTestResult('删除字段', 'info', `删除了字段：${field.label || field.name}`)
}

onMounted(() => {
  loadBlocks()
  addTestResult('页面初始化', 'info', '字段ID修复测试页面已加载')
})
</script>

<style scoped lang="scss">
.field-id-fix-test {
  padding: 20px;
  
  h4, h5 {
    margin: 16px 0 12px 0;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
  }
  
  h5 {
    font-size: 14px;
    margin: 8px 0;
  }
  
  .test-results {
    .test-result {
      margin-bottom: 12px;
    }
  }
  
  .el-code {
    display: block;
    background: #f5f5f5;
    padding: 12px;
    border-radius: 4px;
    white-space: pre-wrap;
    font-family: 'Courier New', monospace;
  }
}
</style>
